
#include "stander_touch_sample.h"
#include <SPI.h>

#define IWIDTH 160
#define IHEIGHT 128

StanderTouchSample::StanderTouchSample() : tft(), img(&tft)
{
}

StanderTouchSample::~StanderTouchSample()
{
}

void StanderTouchSample::touch_calibrate()
{
    uint16_t calData[5];
    uint8_t calDataOK = 0;

    // Calibrate
    tft.fillScreen(TFT_BLACK);
    tft.setCursor(20, 0);
    tft.setTextFont(2);
    tft.setTextSize(1);
    tft.setTextColor(TFT_WHITE, TFT_BLACK);

    tft.println("Touch corners as indicated");

    tft.setTextFont(1);
    tft.println();

    tft.calibrateTouch(calData, TFT_MAGENTA, TFT_BLACK, 15);

    Serial.println();
    Serial.println("// Use this calibration code in setup():");
    Serial.print("  uint16_t calData[5] = ");
    Serial.print("{ ");

    for (uint8_t i = 0; i < 5; i++)
    {
        Serial.print(calData[i]);
        if (i < 4)
            Serial.print(", ");
    }

    Serial.println(" };");
    Serial.print("  tft.setTouch(calData);");
    Serial.println();
    Serial.println();

    tft.fillScreen(TFT_BLACK);

    tft.setTextColor(TFT_GREEN, TFT_BLACK);
    tft.println("Calibration complete!");
    tft.println("Calibration code sent to Serial port.");

    delay(2000);
}

void StanderTouchSample::setup()
{
    Serial.begin(115200);
    Serial.println("ESP32_SPI_9431_v2");

    tft.init();
    tft.setRotation(0);
    // this->touch_calibrate();
    // Use this calibration code in setup():
    // uint16_t calData[5] = {371, 3361, 430, 3435, 4};
    // Use this calibration code in setup():
    // uint16_t calData[5] = {316, 3454, 383, 3492, 4};
    uint16_t calData[5] = {238, 3533, 403, 3507, 4};
    tft.setTouch(calData);
    // tft.setTouch(calData);
    // init_draw();
    // Clear the screen
    tft.fillScreen(TFT_BLACK);
    tft.drawCentreString("Touch screen to test!", tft.width() / 2, tft.height() / 2, 2);
}

void StanderTouchSample::loop()
{
    uint16_t x = 0, y = 0; // To store the touch coordinates

    // Pressed will be set true is there is a valid touch on the screen
    bool pressed = tft.getTouch(&x, &y);

    // Draw a white spot at the detected coordinates
    if (pressed)
    {
        // tft.fillScreen(TFT_BLACK);
        tft.fillCircle(x, y, 5, TFT_WHITE);
        Serial.print("x,y = ");
        Serial.print(x);
        Serial.print(",");
        Serial.println(y);
    }
}